package com.course.auth;

import com.vaadin.server.VaadinSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * Created by Justin on 2017/5/18.
 */
public class SecurityUtils {

    public static boolean isLoggedIn() {
        Authentication auth = getAuth();
        return auth != null && auth.isAuthenticated();
    }

    public static boolean hasRole(String role) {
        role = "ROLE_" + role;
        Authentication auth = getAuth();
        return auth != null && auth.getAuthorities().contains(new SimpleGrantedAuthority(role));
    }

    public static void login(Authentication auth) {
        setAuth(auth);
    }

    public static String getName() {
        return getAuth().getName();
    }

    public static void logout() {
        setAuth(null);
    }

    private static Authentication getAuth() {
        return VaadinSession.getCurrent().getAttribute(Authentication.class);
    }

    private static void setAuth(Authentication auth) {
        VaadinSession.getCurrent().setAttribute(Authentication.class, auth);
    }
}
